package com.example.handler;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.domain.exam.Exam;
import com.example.domain.message.Message;
import com.example.domain.message.MessageText;
import com.example.domain.message.vo.MessageTextVO;
import com.example.domain.user.UserScore;
import com.example.mapper.exam.ExamMapper;
import com.example.mapper.user.UserExamMapper;
import com.example.mapper.user.UserSubmitMapper;
import com.example.redis.service.RedisService;
import com.example.service.IMessageService;
import com.example.service.IMessageTextService;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import oj.common.core.contants.CacheConstants;
import oj.common.core.contants.Constants;
import oj.common.core.enums.ExamListType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class ExamXxlJob {
    @Autowired
    private ExamMapper examMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserSubmitMapper userSubmitMapper;

    @Autowired
    private IMessageTextService messageTextService;
    @Autowired
    private IMessageService messageService;

    @Autowired
    private UserExamMapper userExamMapper;

    @XxlJob("examListOrganizeHandler")
    public void examListOrganizeHandler() {
        //未完赛竞赛列表
        log.info("*** examListOrganizeHandler ***");
        List<Exam> unFinishList = examMapper.selectList(new
                LambdaQueryWrapper<Exam>()
                .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime,
                        Exam::getEndTime)
                .gt(Exam::getEndTime, LocalDateTime.now())
                .eq(Exam::getStatus, Constants.TRUE)
                .orderByDesc(Exam::getCreateTime));
        refreshCache(getUnFinishExamListKey(), unFinishList);
        //历史竞赛列表
        List<Exam> historyExamList = examMapper.selectList(new
                LambdaQueryWrapper<Exam>()
                .select(Exam::getExamId, Exam::getTitle, Exam::getStartTime,
                        Exam::getEndTime)
                .le(Exam::getEndTime, LocalDateTime.now())
                .eq(Exam::getStatus, Constants.TRUE)
                .orderByDesc(Exam::getCreateTime));
        refreshCache(getHistoryListKey(), historyExamList);
    }
    @XxlJob("examResultOrganizeHandler")
    public void examResultOrganizeHandler() {
        log.info("*** examResultOrganizeHandler ***");
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime minusDay = now.minusDays(1);
        List<Exam> examList = examMapper.selectList(new LambdaQueryWrapper<Exam>()
                .select(Exam::getExamId, Exam::getTitle)
                .eq(Exam::getStatus, 1)
                .gt(Exam::getEndTime, minusDay)
                .lt(Exam::getEndTime, now));
        if (CollectionUtil.isEmpty(examList)) {
            return;
        }
        Set<Long> examIdSet = examList.stream().map(Exam::getExamId).collect(Collectors.toSet());
        //这应该有一个mapper层出来进行查看用户提交记录了。
        List<UserScore> userScoreList = userSubmitMapper.selectUserScoreList(examIdSet);
        Map<Long, List<UserScore>> userScoreMap = userScoreList.stream().collect(Collectors.groupingBy(UserScore::getExamId));
        createMessage(examList,userScoreMap);
    }

    private void createMessage(List<Exam> examList, Map<Long, List<UserScore>> userScoreMap) {
        List<MessageText> messageTextList = new ArrayList<>();
        List<Message> messageList = new ArrayList<>();
        for (Exam exam : examList) {
            Long examId = exam.getExamId();
            List<UserScore> userScoreList = userScoreMap.get(examId);
            Integer totalUser = userScoreList.size();
            int examRank=1;
            for(UserScore userScore : userScoreList) {
                String msgTitle =  exam.getTitle() + "——排名情况";
                String msgContent = "您所参与的竞赛：" + exam.getTitle()
                        + "，本次参与竞赛一共" + totalUser + "人， 您排名第"  + examRank + "名！";
                userScore.setExamRank(examRank);
                MessageText messageText = new MessageText();
                messageText.setMessageTitle(msgTitle);
                messageText.setMessageContent(msgContent);
                messageText.setCreateBy(Constants.SYSTEM_USER_ID);
                messageTextList.add(messageText);
                Message message = new Message();
                message.setCreateBy(Constants.SYSTEM_USER_ID);
                message.setSendId(Constants.SYSTEM_USER_ID);
                message.setRecId(userScore.getUserId());
                messageList.add(message);
                examRank++;
            }
            userExamMapper.updateScoreAndRank(userScoreList);
            //这里需要将压入缓存中。
            redisService.rightPushAll(getExamRankListKey(examId),userScoreList);
        }

        //这里开始批量往数据库中插入
        messageTextService.batchInsert(messageTextList);
        Map<String, MessageTextVO> messageTextVOMap = new HashMap<>();
        for (int i = 0; i < messageTextList.size(); i++) {
            MessageText messageText = messageTextList.get(i);
            MessageTextVO messageTextVO = new MessageTextVO();
            String messageTextKey = getMsgDetailKey(messageText.getTextId());
            BeanUtil.copyProperties(messageText,messageTextVO);
            messageTextVOMap.put(messageTextKey,messageTextVO);
            messageList.get(i).setTextId(messageText.getTextId());
        }
        //这里将每一个消息返回的结果给插入到缓存中去。
        redisService.multiSet(messageTextVOMap);
        //批量插入消息和用户之间关系的数据
        messageService.batchInsert(messageList);
        //redis操作，只是针对一个用户进行缓存刷新
        Map<Long, List<Message>> userRedisMap = messageList.stream().collect(Collectors.groupingBy(Message::getRecId));
        Iterator<Map.Entry<Long, List<Message>>> iterator = userRedisMap.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<Long, List<Message>> entry = iterator.next();
            Long recId = entry.getKey();
            String userMsgListKey = getUserMsgListKey(recId);
            List<Long> userMsgTextIdList = entry.getValue().stream().map(Message::getTextId).toList();
            redisService.rightPushAll(userMsgListKey, userMsgTextIdList);
        }
    }

    private String getUserMsgListKey(Long recId) {
        return CacheConstants.USER_MESSAGE_LIST+recId;
    }

    private String getMsgDetailKey(Long textId) {
        return CacheConstants.MESSAGE_DETAIL+textId;
    }

    public void refreshCache(String examListKey, List<Exam> examList) {
        if (CollectionUtil.isEmpty(examList)) {
            return;
        }
        Map<String, Exam> examMap = new HashMap<>();
        List<Long> examIdList = new ArrayList<>();
        for (Exam exam : examList) {
            examMap.put(getDetailKey(exam.getExamId()), exam);
            examIdList.add(exam.getExamId());
        }
        redisService.multiSet(examMap); //刷新详情缓存
        redisService.deleteObject(examListKey);
        redisService.rightPushAll(examListKey, examIdList); //刷新列表缓存
    }
    private String getExamListKey(Integer examListType) {
        if (ExamListType.EXAM_UN_FINISH_LIST.getValue().equals(examListType)) {
            return CacheConstants.EXAM_UNFINISHED_LIST;
        } else if (ExamListType.EXAM_HISTORY_LIST.getValue().equals(examListType)) {
            return CacheConstants.EXAM_HISTORY_LIST;
        } else {
            return "";
        }
    }

    private String getDetailKey(Long examId) {
        return CacheConstants.EXAM_DETAIL + examId;
    }
    private String getHistoryListKey() {
        return CacheConstants.EXAM_HISTORY_LIST;
    }

    private String getUnFinishExamListKey() {
        return CacheConstants.EXAM_UNFINISHED_LIST;
    }

    private String getExamRankListKey(Long examId) {
        return CacheConstants.EXAM_RANK_LIST + examId;
    }
}
